<?php
/**
 * Description of ChatDAO
 *
 * @author Magno
 */
class ChatDAO {

    private $conexao;
    private $leilaoDAO;
    private $clienteDAO;

    public function __construct() {
        $this->conexao = Conexao::getConexao();
        $this->leilaoDAO = new LeilaoDAO();
        $this->clienteDAO = new ClienteDAO();
    }

    public function salvarSimples($chatID,$leilaoID,$usuarioID){
        try {


            $statment = $this->conexao->prepare("INSERT INTO chat(lanceID,leilaoID,usuarioID)
                    VALUES ($chatID,$leilaoID,$usuarioID);");

            return $statment->execute();
        } catch (PDOException $err) {
            throw new Exception("Erro LanceDAO:" . $err->getMessage());
        }
    }

    public function salvar($chat) {

        try {

            if ($chat->getChatID() != null && $chat->getChatID() > 0) {
                //não tem edição
                return $chat;
            } else {

                $statment = $this->conexao->prepare("INSERT INTO chat(chatID,leilaoID,usuarioID,mensagem)
                    VALUES (:chatID,:leilaoID,:usuarioID,:mensagem);");
            }

            if ($statment->execute($chat->toBD())) {

                if ($chat->getChatID() == null || $chat->getChatID() <= 0)
                    $chat->setChatID($this->conexao->lastInsertId());
                return $chat;
            }else {
                $erros = $statment->errorInfo();
                throw new Exception("Erro ChatDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro ChatDAO:" . $err->getMessage());
        }
    }

    public function excluir($chatID) {

        try {

            $statment = $this->conexao->prepare("DELETE FROM chat WHERE chatID = :chatID");
            $statment->bindParam(':chatID', $chatID);

            if (!$statment->execute()) {
                $erros = $statment->errorInfo();
                throw new Exception("Erro ChatDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro ChatDAO:" . $err->getMessage());
        }
    }

    public function listar($pagina = 0, $leilaoID = -1, $usuarioID = -1, $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina);
            $where = $this->getWhere($leilaoID, $usuarioID);
            $chats = array();
            $statment = $this->conexao->query("SELECT * FROM chat u $where $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $chat = new ChatBean($row['chatID'], $row['data']);

                if($carregarDependencias){
                    $chat->setLeilao($this->leilaoDAO->buscarPorID($row['leilaoID']));
                    $chat->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));
                }

                $chats[] =  $chat;
            }

            return $chats;
        } catch (PDOException $err) {
            throw new Exception("Erro ChatDAO:" . $err->getMessage());
        }
    }

    public function listarPorOrdem($pagina = 0, $tamanho = 0, $ordem = "chatID", $direcao = "DESC", $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina,$tamanho);
            $chats = array();
            $statment = $this->conexao->query("SELECT * FROM chat u ORDER BY u.$ordem $direcao $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $chat = new ChatBean($row['chatID'], $row['data']);

                if($carregarDependencias){
                    $chat->setLeilao($this->leilaoDAO->buscarPorID($row['leilaoID']));
                    $chat->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));
                }

                $chats[] = $chat;
            }

            return $chats;
        } catch (PDOException $err) {
            throw new Exception("Erro ChatDAO:" . $err->getMessage());
        }
    }

    public function buscarPorID($chatID, $carregarDependencias = false) {
        try {

            $row = $this->conexao->query("SELECT * FROM chat WHERE chatID = $chatID ")->fetch(PDO::FETCH_SERIALIZE);

            if (isset ($row['chatID']) && $row['chatID'] > 0) {
                $chat = new ChatBean($row['chatID'], $row['data']);

                if($carregarDependencias){
                    $chat->setLeilao($this->leilaoDAO->buscarPorID($row['leilaoID']));
                    $chat->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));
                }

                return $chat;
            } else {
                return null;
            }
        } catch (PDOException $err) {
            throw new Exception("Erro ChatDAO:" . $err->getMessage());
        }
    }

    protected function getWhere($leilaoID = -1,$usuarioID = -1) {

        $where = " WHERE 1 = 1 ";

        if (isset($leilaoID) && $leilaoID > 0) {
            $where = $where . " AND u.leilaoID = $leilaoID ";
        }

        if (isset($usuarioID) && $usuarioID > 0) {
            $where = $where . " AND u.usuarioID = $usuarioID ";
        }

        return $where;
    }

    public function total($leilaoID = -1,$usuarioID = -1) {
        try {

            $where = $this->getWhere($leilaoID, $usuarioID);
            $total = $this->conexao->query("SELECT COUNT(u.chatID) total FROM chat u $where")->fetch(PDO::FETCH_COLUMN);
            return $total;
        } catch (PDOException $err) {
            throw new Exception("Erro ChatDAO:" . $err->getMessage());
        }
    }

}
?>